import { Button, Divider, Input, List, message, Modal, Space, Table, Tabs } from "antd";
import cm from "classnames";
import { useState } from "react";
import style from "./index.less";
import { useAntdTable } from "ahooks";
import { cancelOrder, confirmReceipt, deleteOrder, getOrderList, orderRefundApply } from "@/services/order";
import { money } from "@/utils/money";
import { paymentType, transactionModesType } from "@/pages/OrderDetails/const";
import { items } from "./const";
import { history } from "@umijs/max";
import modal from "antd/es/modal";

const MyOrder = () => {
  const [activeKey, setActiveKey] = useState<string>("");
  const [refundModal, setRefundModal] = useState<boolean>(false);
  const [refundData, setRefundData] = useState<any>({});
  const [refundModalText, setRefundModalText] = useState<string>('');
  const getTableData = ({ current, pageSize }) => {
    return getOrderList({
      pageNum: current,
      pageSize,
      orderStatus: activeKey
    }).then((res) => {
      return {
        list: res.data.list,
        total: res.data.total
      }
    })
  };
  const { tableProps, search } = useAntdTable(getTableData, {
    refreshDeps: [activeKey]
  });

  // 确定收货
  const confirmRe = (item) => {
    modal.confirm({
      title: "是否确认收货",
      onOk() {
        confirmReceipt({orderNo: item.orderNo}).then((res) => {
          if (res.code === 200) {
            message.success("收货成功");
            search.submit()
          } else {
            message.warning(res.messsage)
          }
        })
      },
    });
  }

  // 跳转付款
  const gotoPay = (item) => {
    history.push(`/pay?orderNo=${item.orderNo}&paymentType=${item.paymentType}&payablePrice=${item?.totalPrice}`)
  }

  // 取消订单
  const cancelOrderHandle = (item) => {
    modal.confirm({
      title: "确定要取消该订单吗？",
      onOk() {
        cancelOrder({orderNo: item.orderNo}).then((res) => {
          if (res.code === 200) {
            message.success("取消成功");
            search.submit()
          } else {
            message.warning(res.messsage)
          }
        })
      },
    });
  }

  // 删除订单
  const deleteOrderHandle = (item) => {
    modal.confirm({
      title: "确定要删除该订单吗？",
      onOk() {
        deleteOrder({orderNo: item.orderNo}).then((res) => {
          if (res.code === 200) {
            message.success("删除成功");
            search.submit()
          } else {
            message.warning(res.messsage)
          }
        })
      },
    });
  }

  const refundOrder = () => {
    orderRefundApply({
      orderNo: refundData.orderNo,
      refundReason: refundModalText
    }).then((res) => {
      if (res.code === 200) {
        message.success('申请成功')
        search.submit()
      } else {
        message.warning(res.messsage)
      }
    })
    setRefundModal(false)
  }

  // 查看物流
  const goDetails = (item) => {
    history.push(`/orderDetails/${item.orderNo}`)
  }

  const columns = [
    {
      title: "订单详情",
      dataIndex: "name",
      key: "name",
      width: 500,
      render: (_, item: any) => (
        <div className={cm(style.goods)}>
          {item?.goodsInfo?.map((it, index) => {
            return (
              <div className={cm(style.goods)} key={index}>
                <div
                  className={cm(
                    "managerRow",
                    "managerCenterH",
                    style.goodsTitle,
                    "managerSpread"
                  )}
                >
                  <span>{item?.orderTime}</span>
                  <span>订单编号：{it?.orderNo}</span>
                </div>
                <div
                  className={cm("managerColumn")}
                  style={{ marginTop: "10px" }}
                >
                  <div
                    className={cm("managerRow", "managerSpread")}
                    style={{ width: "100%" }}
                  >
                    <img
                      src={it?.goodsPicture}
                      alt=""
                      style={{ width: "50px", height: "50px" }}
                    />
                    <div
                      className={cm(
                        "managerRow",
                        "managerCenterH",
                        "managerSpread",
                        style.goodsConter
                      )}
                    >
                      <span className={cm(style.goodsTitles)}>
                        {it.goodsName}
                      </span>
                      <span>x{it?.goodsNum}</span>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      ),
    },
    {
      title: "收货人",
      dataIndex: "recipientName",
      key: "recipientName",
    },
    {
      title: "订单金额",
      dataIndex: "totalPrice",
      key: "totalPrice",
      render: (_, item: any) => (
        <div style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column' }}>
          <div>￥: {money(_)}</div>
          <div style={{ color: '#666' }}>{paymentType[item.paymentType] || '微信支付'}</div>
        </div> 
      )
    },
    {
      title: "交易方式",
      dataIndex: "transactionModes",
      key: "transactionModes",
      render: (_, item: any) => (
        <div>{transactionModesType[_] || '在线支付'}</div>
      )
    },
    {
      title: "订单状态",
      dataIndex: "orderStatusName",
      key: "orderStatusName",
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (_, item: any) => (
        <Space>
          {item.orderStatus == "UNPAID" && (
            <Space>
              <Button type="primary" onClick={() => gotoPay(item)}>去支付</Button>
              <Button type="primary" onClick={() => cancelOrderHandle(item)}>取消</Button>
            </Space>
          )}
          {item.orderStatus == "PENDING" && (
            <Space>
              <Button type="primary" onClick={() => goDetails(item)}>查看物流</Button>
              <Button type="primary" onClick={() => confirmRe(item)}>确认收货</Button>
              <Button type="primary" onClick={() => {
                setRefundData(item)
                setRefundModal(true)}
              }>申请退款</Button>
            </Space>
          )}
          {(item.orderStatus == "COMPLETED" || item.orderStatus == "CANCEL") && (
            <Space>
              <Button type="primary" onClick={() => gotoPay(item)}>再次购买</Button>
              <Button type="primary" onClick={() => deleteOrderHandle(item)}>删除订单</Button>
              <Button type="primary" onClick={() => goDetails(item)}>查看详情</Button>
            </Space>
          )}
        </Space>
      ),
    },
  ];
  const onChange = (activeKey: any) => {
    setActiveKey(activeKey);
  };
  return (
    <div className={cm(style.orderStyle)}>
      <Divider style={{ borderColor: "#7cb305" }} orientation="start">
        我的订单
      </Divider>
      <div className={cm(style.conter)}>
        <Tabs items={items} onChange={onChange} defaultActiveKey={activeKey} />
        <div className={cm(style.table)}>
          <Table
            columns={columns}
            {...tableProps}
          />
        </div>
      </div>
      <Modal open={refundModal} onOk={refundOrder} onCancel={() => setRefundModal(false)} okText="确定" cancelText="取消">
        <div style={{ marginBlock: 20 }}>
          <Input.TextArea value={refundModalText} onChange={(e) => {
            setRefundModalText(e.target.value)
          }} />
        </div>
      </Modal>
    </div>
  );
};

export default MyOrder;
